package top.humbleyuan.interview.collection;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author HumbleYuan
 * @Date 2020/2/5 14:47
 * @Des 各种锁的理解
 */
public class TypesOfLock {

    public static void main(String[] args) {
        /**
         * 公平锁/非公平锁
         * Synchronized也是非公平锁,可重入锁
         */
        Lock unFairLock = new ReentrantLock();
        Lock fairLock = new ReentrantLock(true);



        /**
         * 可重入锁
         */
//        ReentrantLockDemo reentrantLockDemo = new ReentrantLockDemo();
//        new Thread(() -> {
//            reentrantLockDemo.get();
//        },"t1").start();
//
//        new Thread(() -> {
//            reentrantLockDemo.get();
//        }, "t2").start();



        /**
         * 自旋锁，手写
         */
        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(() -> {
            spinLockDemo.myLock();

            // 模拟占用5秒钟
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch(Exception e) {
                e.printStackTrace();
            } finally {

            }

            // 释放锁
            spinLockDemo.myUnlock();

        }, "t1").start();

        // 1秒钟之后开启第二个线程，保证t1线程先获得锁
        new Thread(() -> {
            spinLockDemo.myLock();

            // 模拟占用2秒钟
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch(Exception e) {
                e.printStackTrace();
            } finally {

            }

            spinLockDemo.myUnlock();
        },"t2").start();



    }
}

/**
 * 自旋锁
 */
class SpinLockDemo {
    // 线程的原子引用
    AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();

    // 加锁，原子操作
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + ":lock");

        // 若非空，则复制失败，保持自旋
        while (!threadAtomicReference.compareAndSet(null, thread)) {

        }
    }

    // 释放锁
    public void myUnlock() {
        Thread thread = Thread.currentThread();
        threadAtomicReference.compareAndSet(thread, null);
        System.out.println(thread.getName() + ":unlock");
    }
}

/**
 * 可重入锁
 */
class ReentrantLockDemo {

    public synchronized void get() {
        System.out.println(Thread.currentThread().getName() + ":get()");
        set();
    }

    public synchronized void set() {
        System.out.println(Thread.currentThread().getName() + ":set()");
    }
}




